package com.ft.oa.utils;

import com.ft.oa.domain.Attachment;
import com.ft.oa.mapper.attachment.AttachmentMapper;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class UploadFileUtile {
    //附件上传位置
    @Value("${file.upload.url}")
    private String uploadFilePath;
    @Resource
    private AttachmentMapper attachmentMapper;
    /**
     * 附件上传记录
     * @param files
     * relationId  关联的业务id
     * 文件类型id
     * @return
     */
    @Transactional
    public List<Long> upload(MultipartFile files[], String source, String relationId, String sourceId) {
        //记录文件上传信息
        ArrayList<Attachment> fileList = new ArrayList<Attachment>();
        for (MultipartFile myFile:files) {
            Attachment attachment = new Attachment();
            // 获取文件名称
            String filename = FilenameUtils.getBaseName(myFile.getOriginalFilename());
            //获取后缀名称
            String ext = FilenameUtils.getExtension(myFile.getOriginalFilename());
            long size = myFile.getSize();
            String rebuildFileName = filename+System.currentTimeMillis();
            attachment.setFilesize(Long.toString(size));
            attachment.setName(filename);
            attachment.setFileName(rebuildFileName);
            attachment.setType(ext);
            attachment.setRelationId(relationId);
            attachment.setSourceId(sourceId);
            attachment.setSource(source);
            attachment.setPath(uploadFilePath);
            attachmentMapper.insert(attachment);
            fileList.add(attachment);
        }
        List<Long> resultList = null;
        //调用公共方法上传附件
        HashMap<String, List<String>> hashMap = FileUtil.getFileUpload(files, uploadFilePath);
        if(hashMap.isEmpty()){
            return  resultList;
        }else{
            //上传成功后把附件表主键信息传给前端
            resultList = fileList.stream().map(Attachment::getId).collect(Collectors.toList());
            return resultList;
        }
    }
}
